import React, { Component, createContext } from 'react'
import { DeleteOutlined, QuestionCircleOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import {
    Input,
    Select,
    Button,
    Modal,
    Tooltip,
    Row,
    Col,
    Radio,
    InputNumber,
    notification,
    Switch,
    Tabs,
} from 'antd';

const { TabPane } = Tabs;//选项卡
import styles from '@/pages/algorithmModel/dataCenter/style.less';
import indexs from '../style.less';
import { getAlgorithms, getLabelList, getActiveWordvecs } from '@/services/resource';
import { addVersion, getModelLabels } from '@/services/modelCenter';

const FormItem = Form.Item;
const { Option } = Select;

const formItemLayout = {
    labelCol: {
        xs: { span: 24 },
        sm: { span: 11 },
    },
    wrapperCol: {
        xs: { span: 24 },
        sm: { span: 13 },
    },
};

const onlyInt = value => {
    return value.toString().replace(/^(0+)|[^\d+]/g, '');
};

class Edit extends Component {
    constructor(props) {
        super(props);
        this.state = {
            loading: false,
            algorithms: {},//算法
            anotherAlgorithms: [],//算法
            relations: [], // 优化字段列表
            modelLabels: [],//模型下标签
            dictionary: [],// 词典
            wordvecs: [],// 词向量
            dicId: '', // 下拉选择的词典 id
            zd: '',// 优化字段,
            useBuildInDataSet: true,
            anotherModelConfig: {}//另一个训练参数
        };
    }

    componentDidMount() {
        this.queryAlgorithms();
        const { anotherAlgorithmId } = this.props;
        if (anotherAlgorithmId) {
            this.queryAnotherAlgorithms();
        }
        this.queryModelLabels();
        this.queryDictionary();
        this.queryWordvecs()
    }

    // 获取算法
    queryAlgorithms() {
        const { algorithmId } = this.props;
        Boolean(algorithmId) && getAlgorithms(algorithmId).then(res => {
            if (res.retCode === '0') this.setState({ algorithms: res.data, })
        })
    }
    // 获取另一个算法
    queryAnotherAlgorithms() {
        const { anotherAlgorithmId } = this.props;
        Boolean(anotherAlgorithmId) && getAlgorithms(anotherAlgorithmId).then(res => {
            const data = res.data
            const anotherModelConfig = {}
            data.parameters.map(param => {
                anotherModelConfig[param['paramName']] = '';
                param['paramName'] = 'another' + param['paramName']
            })
            if (res.retCode === '0') this.setState({ anotherAlgorithms: data, anotherModelConfig })
        })
    }

    // 获取标签
    queryModelLabels() {
        const { modelId } = this.props;
        getModelLabels(modelId).then(res => {
            if (res.retCode === '0') this.setState({ modelLabels: res.data, })
        })
    }

    // 获取词典
    queryDictionary() {
        getLabelList({}).then(res => {
            if (res.retCode === '0') this.setState({ dictionary: res.data, })
        })
    }

    // 获取词向量
    queryWordvecs() {
        getActiveWordvecs('').then(res => {
            if (res.retCode === '0') this.setState({ wordvecs: res.data, })
        })
    }

    // 提交修改的内容
    handleUserSubmit = e => {
        e.preventDefault();
        const _this = this;
        this.props.form.validateFields((err, values) => {
            if (!err) {
                const { modelId } = _this.props;
                const anotherModelTrainOptimisedList = [];
                const { relations, useBuildInDataSet, anotherModelConfig } = _this.state;
                for (const a in anotherModelConfig) {
                    //另一个训练参数
                    anotherModelConfig[a] = values['another' + a]
                }
                _this.setState({ loading: true, })
                const { type } = this.props
                let data = {}
                if (type === 4 || type === 1 || type === 5) {
                    data = {
                        modelConfig: values,
                        modelId,
                        modelTrainOptimisedList: anotherModelTrainOptimisedList,
                        wordvecId: values.w2vId,
                        anotherWordvecId: values.anotherw2vId,
                        useBuildInDataSet,
                        anotherModelConfig,
                        anotherModelTrainOptimisedList: relations
                    }
                } else {
                    //
                    data = {
                        modelConfig: values,
                        modelId,
                        modelTrainOptimisedList: relations,
                        wordvecId: values.w2vId,
                        anotherWordvecId: values.anotherw2vId,
                        useBuildInDataSet,
                        anotherModelConfig,
                        anotherModelTrainOptimisedList
                    }
                }
                addVersion(data).then(res => {
                    if (res.retCode == '0') {
                        notification['success']({
                            message: '操作成功',
                            key: '操作成功',
                            description: '版本新增成功',
                        });
                        _this.infoToParent(false);
                    } else {
                        _this.setState({ loading: false, })
                    }
                });
            } else {
                const { type } = this.props;
                if (type === 4 || type === 1) {
                    let msg = type === 4 ? '属性算法' : '关系算法'
                    var message = err['anotherw2vId'] ? '实体算法' + err['anotherw2vId']['errors'][0]['message'] : msg + err['w2vId']['errors'][0]['message']
                } else {
                    var message = err['w2vId']['errors'][0]['message']
                }
                notification['warning']({
                    message: message,
                    key: '数据填写不完整',
                    duration: 2.5,
                });
            }
        });
    };

    infoToParent(key, type) {
        this.props.callBack(key);
    }

    onSelectChange(key, val) {
        if (key == 'dicId') {
            this.setState({ dicId: val });
        } else if (key == 'zd') {
            this.setState({ zd: val });
        }
    }

    // 暂存
    save() {
        let { modelLabels, relations, zd, dicId, } = this.state;
        if (dicId == '' || zd == '') {
            notification['error']({
                message: '添加失败',
                key: '词典，优化字段不能为空',
                description: '词典，优化字段不能为空'
            });
            return;
        }
        const arr = relations.filter(val => val.dicId == dicId && val.labelId == zd);
        if (arr.length) {
            notification['warning']({
                message: '添加失败',
                key: '优化字段已存在',
                description: '优化字段已存在'
            });
            return;
        }
        relations.push({ dicId, labelId: zd, labelName: (modelLabels.filter(val => val.labelId == zd))[0]['labelName'] });
        this.setState({ relations, zd: '', dicId: '', });
    }

    //内置数据集开关
    switchOnChange(checked) {
        this.setState({ useBuildInDataSet: checked });
    }

    //切换标签
    tabOnchange(key) {
    }

    // 删除 优化字段
    onDelete(data) {
        let { relations, } = this.state;
        let arr = relations.filter(val => val.dicId !== data.dicId && val.labelId !== data.labelName);
        this.setState({ relations: arr });
    }

    render() {
        const { loading, relations, algorithms, modelLabels, dictionary, wordvecs, dicId, zd, useBuildInDataSet, anotherAlgorithms } = this.state;
        const { form, isShowAddVersonModel, algorithmId, type } = this.props;
        const { getFieldDecorator } = form;
        const { parameters } = algorithms;
        const anoterParameters = anotherAlgorithms.parameters;
        return (
            <Modal
                title={`新增版本`}
                maskClosable={false}
                width={700}
                bodyStyle={{ maxHeight: 620, overflowY: 'auto' }}
                visible={isShowAddVersonModel}
                onCancel={this.infoToParent.bind(this, false)}
                footer={[
                    <Button key="cancel" onClick={this.infoToParent.bind(this, false)}>取消</Button>,
                    <Button key="primary" type='primary' loading={loading} onClick={this.handleUserSubmit}>确定</Button>
                ]}
            >
              {type !==6 && <Form style={{minHeight: 50,}} className={indexs.form_addversion}>
                <Form.Item label='内置数据集' {...formItemLayout}>
                  {getFieldDecorator('switch', {
                    valuePropName: 'checked',
                    initialValue: useBuildInDataSet,
                    rules: [{required: true}]
                  })(
                    <Switch checkedChildren="启"
                            style={{backgroundColor: useBuildInDataSet ? '#29CCB1' : '#BFBFBF'}}
                            unCheckedChildren="禁" onChange={this.switchOnChange.bind(this)}/>
                  )}
                </Form.Item>
              </Form>}
                {
                    (type === 1 || type === 4 || type === 5) ?
                        <Tabs defaultActiveKey="1" size='small' onChange={this.tabOnchange.bind()}>
                            <TabPane tab={'实体算法'} key="1">
                                <Form style={{ minHeight: 300, }} className={indexs.form_addversion}>
                                    {
                                        anoterParameters && anoterParameters.map((val, i) =>
                                            <Form.Item key={i} label={val.paramLabel} {...formItemLayout}>
                                                {getFieldDecorator(val.paramName, {
                                                    rules: [{ required: true, message: `${val.paramLabel}不能为空!` }],
                                                    initialValue: val.value,
                                                })(
                                                    val.paramType == 'int' ?
                                                        <InputNumber step={val.perValue ? val.perValue : 1}
                                                            formatter={onlyInt} parser={onlyInt}
                                                            key={i} min={val.range.from || 0}
                                                            max={val.range.to || 10000} /> :
                                                        val.paramType == 'float' ?
                                                            <InputNumber key={i} min={val.range.from || 0}
                                                                max={val.range.to || 10000} step={val.perValue ? val.perValue :0.01} /> :
                                                            val.paramType === 'bool' ?
                                                                <Radio.Group>
                                                                    <Radio value={'True'}>是</Radio>
                                                                    <Radio value={'False'}>否</Radio>
                                                                </Radio.Group>
                                                                :
                                                                val.paramType == 'enum' ? <Select
                                                                    showSearch
                                                                    style={{ width: 200 }}
                                                                    placeholder={`请选择${val.paramLabel}`}
                                                                    optionFilterProp="children"
                                                                    filterOption={(input, option) =>
                                                                        option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                                                    }
                                                                >
                                                                    {
                                                                        val.enumValues.map((v, i) => <Option key={i}
                                                                            value={v}>{val.paramName === "negativeUsed" ? ['否', '是'][v - 0] : v}</Option>)
                                                                    }
                                                                </Select> :
                                                                    <Select    //val.paramType == 'listbox'
                                                                        showSearch
                                                                        style={{ width: 200 }}
                                                                        optionFilterProp="children"
                                                                        placeholder={`请选择${val.paramLabel}`}
                                                                        filterOption={(input, option) =>
                                                                            option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                                                        }
                                                                    >
                                                                        {
                                                                            wordvecs.map((v, i) => <Option key={i}
                                                                                value={v.wordvecId}>{v.wordvecName}</Option>)
                                                                        }
                                                                    </Select>
                                                )}
                                            </Form.Item>)
                                    }
                                    {
                                        type !== 5 &&
                                        <Form.Item label={'优化字段'} {...formItemLayout}>
                                            {getFieldDecorator('dataName', {
                                                rules: [],
                                            })(
                                                <div>
                                                    <Row style={{
                                                        textAlign: 'center',
                                                        backgroundColor: '#f8f8f8',
                                                        paddingBottom: '8px'
                                                    }} gutter={16}>
                                                        <Col span={9}>
                                                            <div>词典 <Tooltip title={`对应资源库中的标签词典，由对应指定标签的一系列词及同义词组成`}>
                                                                <QuestionCircleOutlined style={{ color: '#8795A1', margin: '0 2px' }} />
                                                            </Tooltip></div>
                                                            <Select
                                                                showSearch
                                                                placeholder="请选择词典"
                                                                value={dicId}
                                                                optionFilterProp="children"
                                                                onChange={this.onSelectChange.bind(this, 'dicId')}
                                                                filterOption={(input, option) =>
                                                                    option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                                                }
                                                            >
                                                                {
                                                                    dictionary.map((val, i) => <Option key={i}
                                                                        value={val.dictionaryLabelId}>{val.dictionaryLabelName}</Option>)
                                                                }
                                                            </Select>
                                                        </Col>
                                                        <Col span={9}>
                                                            <div>优化字段 <Tooltip title={`要优化的数据集中指定标签`}>
                                                                <QuestionCircleOutlined style={{ color: '#8795A1', margin: '0 2px' }} />
                                                            </Tooltip></div>
                                                            <Select
                                                                showSearch
                                                                placeholder="请选择优化字段"
                                                                optionFilterProp="children"
                                                                value={zd}
                                                                onChange={this.onSelectChange.bind(this, 'zd')}
                                                                filterOption={(input, option) =>
                                                                    option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                                                }
                                                            >
                                                                {
                                                                    modelLabels.map((val, i) => <Option key={i}
                                                                        value={val.labelId}>{val.labelName}</Option>)
                                                                }
                                                            </Select>
                                                        </Col>
                                                        <Col span={5} style={{ paddingTop: 40 }}>
                                                            <a type="link" onClick={this.save.bind(this)}>+添加</a>
                                                        </Col>
                                                    </Row>
                                                    <div className={styles.relationBox} style={{ maxHeight: 180 }}>
                                                        {
                                                            relations.map((val, index) => <Row key={index} style={{
                                                                border: '1px solid #e8e8e8',
                                                                marginBottom: 8
                                                            }}>
                                                                <Col style={{
                                                                    borderRight: '1px solid #e8e8e8',
                                                                    padding: '0 6px'
                                                                }} span={11}>
                                                                    {
                                                                        dictionary.filter(item => item.dictionaryLabelId == val.dicId)[0]['dictionaryLabelName']
                                                                    }
                                                                </Col>
                                                                <Col style={{
                                                                    borderRight: '1px solid #e8e8e8',
                                                                    padding: '0 6px'
                                                                }} span={11}>{val.labelName}</Col>
                                                                <Col style={{ textAlign: 'center', height: 32 }}
                                                                    span={2}><DeleteOutlined
                                                                    style={{ cursor: 'pointer' }}
                                                                    onClick={this.onDelete.bind(this, {
                                                                        dicId: val.dicId,
                                                                        labelName: val.labelName
                                                                    })} /></Col>
                                                            </Row>)
                                                        }
                                                    </div>
                                                </div>
                                            )}
                                        </Form.Item>
                                    }
                                </Form>
                            </TabPane>
                            <TabPane tab={type === 4 ? '属性算法' : (type === 5 ? '事件算法' : '关系算法')} key="2">
                                <Form style={{ minHeight: 300, }} className={indexs.form_addversion}>

                                    {
                                        parameters && parameters.map((val, i) =>
                                            <Form.Item key={i} label={val.paramLabel} {...formItemLayout}>
                                                {getFieldDecorator(val.paramName, {
                                                    rules: [{ required: val.paramLabel==='类别阈值'?false:true, message: `${val.paramLabel}不能为空!` }],
                                                    initialValue: val.value,
                                                })(
                                                    val.paramType === 'int' ?
                                                        <InputNumber step={val.perValue ? val.perValue : 1}
                                                            formatter={onlyInt} parser={onlyInt}
                                                            key={i} min={val.range.from || 0}
                                                            max={val.range.to || 10000} /> :
                                                        val.paramType === 'float' ?
                                                            <InputNumber key={i} min={val.range.from || 0}
                                                                max={val.range.to || 10000} step={val.perValue ? val.perValue :0.01} /> :
                                                            val.paramType === 'enum' ? <Select
                                                                showSearch
                                                                style={{ width: 200 }}
                                                                placeholder={`请选择${val.paramLabel}`}
                                                                optionFilterProp="children"
                                                                filterOption={(input, option) =>
                                                                    option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                                                }
                                                            >
                                                                {
                                                                    val.enumValues.map((v, i) => <Option key={i}
                                                                        value={v}>{val.paramName === "negativeUsed" ? ['否', '是'][v - 0] : v}</Option>)
                                                                }
                                                            </Select> :
                                                                <Select    //val.paramType == 'listbox'
                                                                    showSearch
                                                                    style={{ width: 200 }}
                                                                    optionFilterProp="children"
                                                                    placeholder={`请选择${val.paramLabel}`}
                                                                    filterOption={(input, option) =>
                                                                        option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                                                    }
                                                                >
                                                                    {
                                                                        wordvecs.map((v, i) => <Option key={i}
                                                                            value={v.wordvecId}>{v.wordvecName}</Option>)
                                                                    }
                                                                </Select>
                                                )}
                                            </Form.Item>)
                                    }
                                </Form>
                            </TabPane>
                        </Tabs>
                        :
                        <Form style={{ minHeight: 300, }} className={indexs.form_addversion}>
                            {
                                parameters && parameters.map((val, i) =>
                                    <Form.Item key={i} label={val.paramLabel} {...formItemLayout}>
                                        {getFieldDecorator(val.paramName, {
                                            rules: [{ required: true, message: `${val.paramLabel}不能为空!` }],
                                            initialValue: val.value,
                                        })(
                                            val.paramType == 'int' ?
                                                <InputNumber formatter={onlyInt} parser={onlyInt} step={val.perValue ? val.perValue : 1} key={i}
                                                min={val.range.from || 0} max={val.range.to || 10000} />
                                                :
                                                val.paramType == 'float' ?
                                                    <InputNumber key={i} min={val.range.from || 0}
                                                        max={val.range.to || 10000}
                                                                 step={val.perValue ? val.perValue : 0.01}
                                                                 precision={1}
                                                    />
                                                    :
                                                    val.paramType === 'bool' ?
                                                        <Radio.Group>
                                                            <Radio value={'True'}>是</Radio>
                                                            <Radio value={'False'}>否</Radio>
                                                        </Radio.Group>
                                                        :
                                                        val.paramType == 'enum' ? <Select
                                                            showSearch
                                                            style={{ width: 200 }}
                                                            placeholder={`请选择${val.paramLabel}`}
                                                            optionFilterProp="children"
                                                            filterOption={(input, option) =>
                                                                option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                                            }
                                                        >
                                                            {
                                                                val.enumValues.map((v, i) => <Option key={i}
                                                                    value={v}>{val.paramName === "negativeUsed" ? ['否', '是'][v - 0] : v}</Option>)
                                                            }
                                                        </Select> :
                                                            <Select    //val.paramType == 'listbox'
                                                                showSearch
                                                                style={{ width: 200 }}
                                                                optionFilterProp="children"
                                                                placeholder={`请选择${val.paramLabel}`}
                                                                filterOption={(input, option) =>
                                                                    option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                                                }
                                                            >
                                                                {
                                                                    wordvecs.map((v, i) => <Option key={i}
                                                                        value={v.wordvecId}>{v.wordvecName}</Option>)
                                                                }
                                                            </Select>
                                        )}
                                    </Form.Item>)
                            }
                            {type === 0 &&
                                <Form.Item label={'优化字段'} {...formItemLayout}>
                                    {getFieldDecorator('dataName', {
                                        rules: [],
                                    })(
                                        <div>
                                            <Row style={{
                                                textAlign: 'center',
                                                backgroundColor: '#f8f8f8',
                                                paddingBottom: '8px'
                                            }} gutter={16}>
                                                <Col span={9}>
                                                    <div>词典 <Tooltip title={`对应资源库中的标签词典，由对应指定标签的一系列词及同义词组成`}>
                                                        <QuestionCircleOutlined style={{ color: '#8795A1', margin: '0 2px' }} />
                                                    </Tooltip></div>
                                                    <Select
                                                        showSearch
                                                        placeholder="请选择词典"
                                                        value={dicId}
                                                        optionFilterProp="children"
                                                        onChange={this.onSelectChange.bind(this, 'dicId')}
                                                        filterOption={(input, option) =>
                                                            option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                                        }
                                                    >
                                                        {
                                                            dictionary.map((val, i) => <Option key={i}
                                                                value={val.dictionaryLabelId}>{val.dictionaryLabelName}</Option>)
                                                        }
                                                    </Select>
                                                </Col>
                                                <Col span={9}>
                                                    <div>优化字段 <Tooltip title={`要优化的数据集中指定标签`}>
                                                        <QuestionCircleOutlined style={{ color: '#8795A1', margin: '0 2px' }} />
                                                    </Tooltip></div>
                                                    <Select
                                                        showSearch
                                                        placeholder="请选择优化字段"
                                                        optionFilterProp="children"
                                                        value={zd}
                                                        onChange={this.onSelectChange.bind(this, 'zd')}
                                                        filterOption={(input, option) =>
                                                            option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                                        }
                                                    >
                                                        {
                                                            modelLabels.map((val, i) => <Option key={i}
                                                                value={val.labelId}>{val.labelName}</Option>)
                                                        }
                                                    </Select>
                                                </Col>
                                                <Col span={5} style={{ paddingTop: 40 }}>
                                                    <a type="link" onClick={this.save.bind(this)}>+添加</a>
                                                </Col>
                                            </Row>
                                            <div className={styles.relationBox} style={{ maxHeight: 180 }}>
                                                {
                                                    relations.map((val, index) => <Row key={index} style={{
                                                        border: '1px solid #e8e8e8',
                                                        marginBottom: 8
                                                    }}>
                                                        <Col style={{ borderRight: '1px solid #e8e8e8', padding: '0 6px' }}
                                                            span={11}>
                                                            {
                                                                dictionary.filter(item => item.dictionaryLabelId == val.dicId)[0]['dictionaryLabelName']
                                                            }
                                                        </Col>
                                                        <Col style={{ borderRight: '1px solid #e8e8e8', padding: '0 6px' }}
                                                            span={11}>{val.labelName}</Col>
                                                        <Col style={{ textAlign: 'center', height: 32 }} span={2}><DeleteOutlined
                                                            style={{ cursor: 'pointer' }}
                                                            onClick={this.onDelete.bind(this, {
                                                                dicId: val.dicId,
                                                                labelName: val.labelName
                                                            })} /></Col>
                                                    </Row>)
                                                }
                                            </div>
                                        </div>
                                    )}
                                </Form.Item>}
                        </Form>
                }


            </Modal>
        );
    }
}

const Add = Form.create()(Edit);

export default Add
